package com.heima.wemedia.service.impl;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmNewsMaterialServiceImpl wmNewsMaterialService;
    private static final List<String> IMAGE_TYPE_LIST = Arrays.asList("png", "bmp", "gif", "jpeg", "jpg");

    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) {
        //1.判断文件的合法性
        //1.1 文件不能为空
        if(file.isEmpty() || file.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        try {
            //1.2 文件必须是图片
            String type = FileTypeUtil.getType(file.getInputStream());
            if(!IMAGE_TYPE_LIST.contains(type)){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "不是图片");
            }

            //2.生成唯一文件名： 前缀名+后缀名
            String filePrefixName = IdUtil.fastSimpleUUID(); //文件的前缀名（绝对唯一）
            String filePostfixName = "." + type;
            String fileName = filePrefixName + filePostfixName;

            //3.上传文件到MinIO
            String url = fileStorageService.uploadImgFile(null, fileName, file.getInputStream());

            //4.保存素材
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(url);
            wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);

            return ResponseResult.okResult(url);

        } catch (IOException e) {
            e.printStackTrace();

            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "上传出现问题");
        }
    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {

//1. 设置分页参数的默认值
        dto.checkParam();
        //2. 执行分页查询  select * from wm_material where user_id=? [and is_collection=?] order by created_time desc limit ?,?
        IPage<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
//        this.page(page, Wrappers.<WmMaterial>lambdaQuery()
//                .eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId())
//                .eq(dto.getIsCollection()>0, WmMaterial::getIsCollection, dto.getIsCollection())
//                .orderByDesc(WmMaterial::getCreatedTime)
//        );
        this.lambdaQuery()
                .eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId())
                .eq(dto.getIsCollection()>0,WmMaterial::getIsCollection, dto.getIsCollection())
                .orderByDesc(WmMaterial::getCreatedTime)
                .page(page);

        //3. 封装分页响应结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int)page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {
//1.判断参数的合法性
        if(id==null || id<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断数据是否存在 select count(*) from wm_material where id=?
        Integer count = this.lambdaQuery().eq(WmMaterial::getId, id).count();
        if(count<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.判断素材是否被引用 select count(*) from wm_news_material where material_id=?
        Integer countRelation = wmNewsMaterialService.lambdaQuery().eq(WmNewsMaterial::getMaterialId, id).count();
        if(countRelation>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "素材被引用无法删除");
        }

        //4.删除minio中的素材
        WmMaterial wmMaterial = this.getById(id);
        fileStorageService.delete(wmMaterial.getUrl());


        //5.删除素材表数据
        this.removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        //1.判断参数的合法性
        if(id==null || id<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断数据是否存在 select count(*) from wm_material where id=?
        Integer count = this.lambdaQuery().eq(WmMaterial::getId, id).count();
        if(count<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.执行更新 update wm_material set is_collection=0 where id=?
        this.lambdaUpdate()
                .eq(WmMaterial::getId,id)
                .set(WmMaterial::getIsCollection, 0)
                .update();

        //this.update(Wrappers.<WmMaterial>lambdaUpdate().eq(WmMaterial::getId,id).set(WmMaterial::getIsCollection, 0));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        //1.判断参数的合法性
        if(id==null || id<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断数据是否存在 select count(*) from wm_material where id=?
        Integer count = this.lambdaQuery().eq(WmMaterial::getId, id).count();
        if(count<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.执行更新 update wm_material set is_collection=1 where id=?
        this.lambdaUpdate().eq(WmMaterial::getId,id).set(WmMaterial::getIsCollection, 1).update();

        //this.update(Wrappers.<WmMaterial>lambdaUpdate().eq(WmMaterial::getId,id).set(WmMaterial::getIsCollection, 1));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
